#include "mythread.h"

myThread::myThread(QObject *parent)
    : QThread{parent}
{
    m_state = false;
    mutex = new QMutex;
    QMutexLocker locker(mutex);
    curPort = new QSerialPort;
}

void myThread::stopThread()
{
    m_state = false;
}

void myThread::startThread(int SerialPortIndex,qint32 baud,int dataBits,int pairtyIndex,int stopBitsIndex)
{
    mutex->lock();

    m_SerialPortIndex = SerialPortIndex;
    m_baud = baud;
    m_dataBits = dataBits;
    m_pairtyIndex = pairtyIndex;
    m_stopBitsIndex = stopBitsIndex;
    mutex->unlock();
    if(!isRunning())
    {
        start(Priority::HighestPriority);
    }
}

void myThread::run()
{
    // curPort = new QSerialPort;
    if(!curPort->isOpen())
    {
        QList<QSerialPortInfo> comList = QSerialPortInfo::availablePorts();
        QSerialPortInfo portInfo = comList.at(m_SerialPortIndex);
        curPort->setPort(portInfo);
        curPort->setBaudRate(m_baud);
        curPort->setDataBits(QSerialPort::DataBits(m_dataBits));
        QSerialPort::Parity pairty;
        switch (m_pairtyIndex) {
        case 0:
            pairty = QSerialPort::Parity::NoParity;
            break;
        case 1:
            pairty = QSerialPort::Parity::EvenParity;
            break;
        case 2:
            pairty = QSerialPort::Parity::OddParity;
            break;
        case 3:
            pairty = QSerialPort::Parity::SpaceParity;
            break;
        case 4:
            pairty = QSerialPort::Parity::MarkParity;
            break;
        default:
            pairty = QSerialPort::Parity::NoParity;
            break;
        }
        curPort->setParity(pairty);
        QSerialPort::StopBits stopBits;
        switch (m_stopBitsIndex) {
        case 0:
            stopBits = QSerialPort::StopBits::OneStop;
            break;
        case 1:
            stopBits = QSerialPort::StopBits::OneAndHalfStop;
            break;
        case 2:
            stopBits = QSerialPort::StopBits::TwoStop;
            break;
        default:
            stopBits = QSerialPort::StopBits::OneStop;
            break;
        }
        curPort->setStopBits(stopBits);
    }
    if(curPort->open(QSerialPort::OpenModeFlag::ReadWrite))
    {
        m_state = true;
        emit stateReport("串口打开成功1");
    }
    else
    {
        m_state = false;
        emit stateReport("串口打开失败1");
    }
    while(m_state)
    {
        curPort->write("hello\r\n");
        if(curPort->waitForBytesWritten(-1))
        {
            qDebug()<<"send sucess";
        }
        // read response
        if (curPort->waitForReadyRead(-1)) {
            QByteArray responseData = curPort->readAll();
            while (curPort->waitForReadyRead(10))
                responseData += curPort->readAll();
            qDebug()<<"rev"<<responseData;
        }
    }
    m_state = false;
    emit stateReport("串口关闭2");
}
